<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\YuanfenjuService;
use app\common\model\FengshuiXuankongLog;

/**
 * 玄空风水盘接口
 * @ApiWeigh (97)
 */
class FengshuiXuankong extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 玄空风水盘
     * 
     * @ApiTitle    (玄空风水盘)
     * @ApiSummary  (根据宅主生辰信息进行玄空风水排盘分析)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/fengshui_xuankong/index)
     * 
     * @ApiParams   (name="born_year", type="integer", required=true, description="宅主出生农历年，如：1988")
     * @ApiParams   (name="sex", type="integer", required=true, description="性别：0=男，1=女")
     * @ApiParams   (name="yun_model", type="integer", required=true, description="元运：0=一运,1=二运,2=三运,3=四运,4=五运,5=六运,6=七运,7=八运,8=九运")
     * @ApiParams   (name="shan_model", type="integer", required=true, description="山向：0=壬山丙向,1=子山午向,...,23=亥山巳向")
     * @ApiParams   (name="ti_model", type="integer", required=false, description="是否用替卦：0=否,1=是", default=0)
     * @ApiParams   (name="long_model", type="integer", required=false, description="是否排龙诀：0=否,1=是", default=0)
     * @ApiParams   (name="long_shui_kou", type="integer", required=false, description="水口在：0=王,1=子,...,23=亥", default=null)
     * @ApiParams   (name="ming_model", type="integer", required=false, description="是否排命盘：0=否,1=是", default=0)
     * @ApiParams   (name="ming_liu_year", type="integer", required=false, description="农历流年，如：1990", default=null)
     * @ApiParams   (name="ming_liu_month", type="integer", required=false, description="农历流月，如：8", default=null)
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "born_info": {                    // 出生信息
            "born_year": 1988,              // 出生年
            "sex": "男",                    // 性别
            "yun_model": "八运",            // 元运
            "shan_model": "艮山坤向"        // 山向
          },
          "gua_info": {                     // 卦象信息
            "gua_name": "乾卦",             // 卦名
            "gua_detail": "...",            // 卦象详解
            "ti_gua": "兑卦"                // 替卦(当ti_model=1时)
          },
          "long_jue": {                     // 龙诀(当long_model=1时)
            "long_xiang": "...",            // 龙象
            "shui_kou": "..."               // 水口(当指定long_shui_kou时)
          },
          "ming_pan": {                     // 命盘(当ming_model=1时)
            "liu_nian": "...",              // 流年
            "liu_yue": "...",               // 流月
            "analysis": "..."               // 分析
          }
        }
      })
     */
    public function index()
    {
        $params = [
            'born_year' => $this->request->post('born_year', '', 'intval'),
            'sex' => $this->request->post('sex', 0, 'intval'),
            'yun_model' => $this->request->post('yun_model', '', 'intval'),
            'shan_model' => $this->request->post('shan_model', '', 'intval'),
            'ti_model' => $this->request->post('ti_model', 0, 'intval'),
            'long_model' => $this->request->post('long_model', 0, 'intval'),
            'long_shui_kou' => $this->request->post('long_shui_kou', null, 'intval'),
            'ming_model' => $this->request->post('ming_model', 0, 'intval'),
            'ming_liu_year' => $this->request->post('ming_liu_year', null, 'intval'),
            'ming_liu_month' => $this->request->post('ming_liu_month', null, 'intval')
        ];

        // 必填参数验证
        $required = ['born_year', 'sex', 'yun_model', 'shan_model'];
        foreach ($required as $field) {
            if (!isset($params[$field])) {
                $this->error(__('Parameter %s can not be empty', $field));
            }
        }

        // 参数验证
        if (!in_array($params['sex'], [0, 1])) {
            $this->error(__('Invalid sex value'));
        }
        if ($params['yun_model'] < 0 || $params['yun_model'] > 8) {
            $this->error(__('Invalid yun_model value'));
        }
        if ($params['shan_model'] < 0 || $params['shan_model'] > 23) {
            $this->error(__('Invalid shan_model value'));
        }

        try {
            $result = YuanfenjuService::instance()->request('/Fengshui/xuankong', $params);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'] ?? '玄空风水盘分析失败');
            }
            
            // 记录查询日志
            FengshuiXuankongLog::create(array_merge(
                $params,
                [
                    'user_id' => $this->auth->id,
                    'response_data' => json_encode($result['data'], JSON_UNESCAPED_UNICODE)
                ]
            ));
            
            $this->success('获取成功', $result['data']);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }

    /**
     * 查询历史列表
     * 
     * @ApiTitle    (玄空风水盘历史记录)
     * @ApiSummary  (获取用户的玄空风水盘查询历史记录)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/fengshui_xuankong/history)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default=1)
     * @ApiParams   (name="limit", type="integer", required=false, description="每页数量", default=10)
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "total": 100,                     // 总记录数
          "list": [{
            "id": 1,                        // 记录ID
            "born_year": 1988,              // 出生年
            "sex": 0,                       // 性别
            "sex_text": "男",               // 性别文字
            "yun_model": 7,                 // 元运
            "yun_model_text": "八运",       // 元运文字
            "shan_model": 3,                // 山向
            "shan_model_text": "艮山坤向",  // 山向文字
            "ti_model": 0,                  // 是否用替卦
            "long_model": 0,                // 是否排龙诀
            "long_shui_kou": null,          // 水口位置
            "ming_model": 0,                // 是否排命盘
            "ming_liu_year": null,          // 流年
            "ming_liu_month": null,         // 流月
            "createtime": 1677123456,       // 创建时间戳
            "createtime_text": "2023-02-23 12:34:56" // 创建时间文字
          }]
        }
      })
     */
    public function history()
    {
        $page = $this->request->get('page', 1, 'intval');
        $limit = $this->request->get('limit', 10, 'intval');
        
        $total = FengshuiXuankongLog::where('user_id', $this->auth->id)->count();
        $list = FengshuiXuankongLog::where('user_id', $this->auth->id)
            ->field('id,born_year,sex,yun_model,shan_model,ti_model,long_model,long_shui_kou,ming_model,ming_liu_year,ming_liu_month,createtime')
            ->order('id desc')
            ->page($page, $limit)
            ->select();
        
        $this->success('获取成功', [
            'total' => $total,
            'list' => $list
        ]);
    }

    /**
     * 查询历史详情
     * 
     * @ApiTitle    (玄空风水盘历史详情)
     * @ApiSummary  (获取指定玄空风水盘记录的详细信息)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/fengshui_xuankong/detail)
     * @ApiParams   (name="id", type="integer", required=true, description="记录ID")
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "id": 1,                          // 记录ID
          "user_id": 1,                     // 用户ID
          "born_year": 1988,                // 出生年
          "sex": 0,                         // 性别
          "sex_text": "男",                 // 性别文字
          "yun_model": 7,                   // 元运
          "yun_model_text": "八运",         // 元运文字
          "shan_model": 3,                  // 山向
          "shan_model_text": "艮山坤向",    // 山向文字
          "ti_model": 0,                    // 是否用替卦
          "long_model": 0,                  // 是否排龙诀
          "long_shui_kou": null,            // 水口位置
          "ming_model": 0,                  // 是否排命盘
          "ming_liu_year": null,            // 流年
          "ming_liu_month": null,           // 流月
          "createtime": 1677123456,         // 创建时间戳
          "createtime_text": "2023-02-23 12:34:56", // 创建时间文字
          "response_data": {                // 原始接口返回数据
            // ... 同玄空风水盘接口返回的data部分
          }
        }
      })
     */
    public function detail()
    {
        $id = $this->request->get('id', 0, 'intval');
        
        $log = FengshuiXuankongLog::where('user_id', $this->auth->id)
            ->where('id', $id)
            ->find();
            
        if (!$log) {
            $this->error('记录不存在');
        }
        
        $log['response_data'] = json_decode($log['response_data'], true);
        
        $this->success('获取成功', $log);
    }

    /**
     * 清空历史记录
     * 
     * @ApiTitle    (清空玄空风水盘历史记录)
     * @ApiSummary  (清空当前用户的所有玄空风水盘查询记录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/fengshui_xuankong/clear_history)
     * 
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "清空成功",
     *   "data": null
     * })
     */
    public function clearHistory()
    {
        try {
            FengshuiXuankongLog::where('user_id', $this->auth->id)->delete();
            $this->success('清空成功');
        } catch (\think\exception\PDOException $e) {
            $this->error('清空失败：' . $e->getMessage());
        }
    }
}